<template>
	<div class="mobile-dialog-body" ref="dialogBody">
		<!--猜你想问-->
		<mobile-dialog-preset @scrollToBottom="scrollToBottom"></mobile-dialog-preset>
		<div
			v-for="(item, index) of messageList" :key="index"
			class="dialog-item"
			:class="{
				client: item.message_type === '1',
				adviser: item.message_type === '2'
			}">
			<div v-if="item.message_body_type == 'text' || !item.message_body_type"  class="item-inner">
				<!--文本-->
				<div class="item-content">
					<span v-html="item.message.content.replace(/\n/g, '<br />')"></span>
				</div>
			</div>
			<div v-else class="item-inner" :class="{'is-img': item.message_body_type === 'callingCard'}">
				<!--名片-->
				<img  v-if="item.message_body_type === 'callingCard'" :src="CallingCardImg"/>
				<!--h5页面card-->
				<div v-else-if="item.message_body_type === 'pageUrl'" class="page-card" @click="clickShowIframe(item.message.url)">
					<div class="card-title">
						{{item.message.title}}
					</div>
					<div class="img-wrap" @click="clickShowIframe(item.message.url)">
						<img v-if="item.message.bizType === '1' || item.message.bizType === '4'" :src="ProposalImg" class="img"/>
						<img v-else :src="PolicyImg" class="img"/>
						<span class="remark" :class="{proposal: item.message.bizType === '1' || item.message.bizType === '4'}">{{item.message.content}}</span>
					</div>
				</div>
				<!--视频card-->
				<div v-else-if="item.message_body_type === 'videoCard'" class="page-card">
					<div class="card-title">
						{{item.message.title}}
					</div>
					<video :src="item.message.url" controls class="video"></video>
				</div>
			</div>
		</div>
		<!--h5页面打开展示-->
		<div v-if="showIframe" class="iframe-wrapper">
			<div class="title">
				<svg-icon iconClass="close2" @svgEvent="clickCloseIframe"></svg-icon>
			</div>
			<iframe
				ref="iframe"
				frameborder="0"
				:src="iframeUrl"></iframe>
		</div>
	</div>
</template>

<script>
import MobileDialogPreset from '@/components/aia-mobile/mobile-dialog-preset.vue'
import { mapState, mapMutations } from "vuex"
import CallingCardImg from '@/assets/images/calling-card.png'
import ProposalImg from '@/assets/images/proposal.png'
import PolicyImg from '@/assets/images/policy.png'
export default {
	name: 'MobileDialogBody',
	components: {
		MobileDialogPreset,
	},
	data() {
		return {
			CallingCardImg,
			ProposalImg,
			PolicyImg,
			socket: null,
			heartCheck: {
				// timeout: 50000, // 50，秒发一次心跳
				timeout: 25000, // 25秒发一次心跳
				timeoutObj: null
			},
			reconnectAttempts: 0, // 重连尝试次数
			maxReconnectAttempts: 5, // 最大重连尝试次数
			reconnectInterval: 1000, // 初始重连间隔时间，单位毫秒
			needReconnect: true, // 是否需要重连
			showIframe: false,
			iframeUrl: '', // 页面链接
		}
	},
	computed: {
		...mapState('aia-mobile', ['mobileSessionInfo', 'messageList', 'scrollMobileMessage'])
	},
	watch: {
		scrollMobileMessage(val) {
			if (val) {
				this.scrollToBottom()
				this.setScrollMobileMessage(false)
			}
		}
	},
	created() {
		this.getHistoryMessage()
	},
	beforeDestroy() {
		this.needReconnect = false
		if(this.socket) {
			this.socket.close()
		}
	},
	activated() {
		this.scrollToBottom()
	},
	methods: {
		...mapMutations('aia-mobile', ['setMessageList', 'pushMessageList', 'setScrollMobileMessage']),
		// 滚动到底部
		scrollToBottom() {
			let dialogBody = this.$refs.dialogBody
			dialogBody.scroll({
				top: dialogBody.scrollHeight,
				// behavior: 'smooth'
			})
		},
		// 根据sessionId查询会话中的所有消息
		getHistoryMessage() {
			this.$usePost(this.$url.getHistoryMessage, {
				session_id: this.mobileSessionInfo.session_id,
				user_type: '1',    // 1.查询用户和代理人的消息 2.查询代理人和ai的消息
				// current: 1, // 缺省时查最后一页数据
				size: 100
			}).then(res => {
				let messageList = res.data.records.filter(u => u.message_type === '1' || u.message_type === '2')
				this.setMessageList(messageList)
				this.$nextTick(() => {
					this.needReconnect = true
					this.createSocket()
				})
				setTimeout(() => {
					this.scrollToBottom()
				}, 300)
			})
		},
		// 创建websocket
		createSocket () {
			if (typeof WebSocket === 'undefined') {
				console.log('您的浏览器不支持WebSocket')
			} else {
				console.log('您的浏览器支持WebSocket')
				if (this.socket !== null) {
					this.socket.close()
					this.socket = null
					clearTimeout(this.heartCheck.timeoutObj)
				}
				this.socket = new WebSocket(LOCAL_CONFIG.clientWs + this.mobileSessionInfo.client_id)
				// 打开事件
				this.socket.onopen = () => {
					console.log('移动端模拟页面websocket已打开')
					// this.startHeartCheck() // 心跳检测重置
					console.log('移动端模拟页面websocket连接成功!' + new Date().toLocaleString())
				}
				// 获得消息事件
				this.socket.onmessage = msg => {
					this.startHeartCheck() // 如果获取到消息，心跳检测重置
					// console.log(msgData)
					let msgData = JSON.parse(msg.data)
					if (msgData.data) {
						let data = msgData.data
						let item = {
							clientId: data.clientId,
							message_type:  '2', // message_type 1.用户->代理人 2.代理人->用户 3.代理人->大模型 4.大模型->代理人
							message_body_type: data.aiccMsgType,
							create_time: data.createTime || '',
							message: {}
						}
						item.message = data.aiccMsgContent
						this.pushMessageList(item)
						this.$nextTick(() => {
							this.scrollToBottom()
						})
					}
				}
				// 关闭事件
				this.socket.onclose = () => {
					console.log('移动端模拟页面websocket已关闭' + new Date().toLocaleString())
					this.needReconnect && this.reconnectWebSocket(); // 添加断线重连逻辑
				}
				// 发生了错误事件
				this.socket.onerror = function () {
					console.log('移动端模拟页面websocket发生了错误' + new Date().toLocaleString())
				}
			}
		},
		startHeartCheck () {
			clearTimeout(this.heartCheck.timeoutObj)
			this.heartCheck.timeoutObj = setTimeout(() => {
				// 这里发送一个心跳，后端收到后，返回一个心跳消息，
				// onmessage拿到返回的心跳就说明连接正常
				this.socket.send('2')
				// console.log('ping' + new Date().toLocaleString())
			}, this.heartCheck.timeout)
		},
		// 重连方法
		reconnectWebSocket() {
			if (this.reconnectAttempts < this.maxReconnectAttempts) {
				console.log(`移动端模拟页面websocket尝试重新连接，当前尝试次数：${this.reconnectAttempts}`);
				setTimeout(() => {
					this.createSocket(); // 尝试重新创建WebSocket连接
					this.reconnectAttempts++; // 重连次数加一
					// 可选：逐渐增加重连间隔
					// this.reconnectInterval = this.reconnectInterval * 2;
				}, this.reconnectInterval);
			} else {
				console.error('移动端模拟页面websocket达到最大重连次数，不再尝试重连');
				this.reconnectAttempts = 0; // 重置重连次数，以便下次连接时重新计算
				this.socket = null; // 确保状态正确
			}
		},
		// 显示iframe页面
		clickShowIframe(url) {
			this.iframeUrl = url
			this.showIframe = true
		},
		// 关闭iframe页面
		clickCloseIframe() {
			this.showIframe = false
			this.iframeUrl = ''
		},
	}
}
</script>

<style lang="scss" scoped>
.mobile-dialog-body{
	overflow: hidden auto;
	padding: 0.24rem .32rem;
	flex:1;
	.dialog-item{
		margin-top: 0.24rem;
		display: flex;
		justify-content: flex-start;
		font-size: 0.28rem;
		.item-inner{
			padding: 0.24rem 0.2rem;
			position:relative;
			background: #FFFFFF;
			border-radius: 0.16rem;
			max-width: 5.7rem;
			&::before{
				content: " ";
				border-style: solid;
				border-color: transparent;
				border-right-color: #fff;
				border-width: 0.14rem;
				border-left-width: 0;
				position: absolute;
				left: -0.14rem;
				// top: calc(50% - 0.14rem);
				top: 0.3rem;
			}
			&.is-img{
				padding: 0;
				background: none;
				overflow: hidden;
				&::before{
					display: none;
				}
			}
			.page-card{
				cursor: pointer;
				.card-title{
					font-weight: bold;
					margin-bottom: 0.20rem;
				}
				.img-wrap{
					position: relative;
					text-align: center;
					cursor: pointer;
					.img{
						width: 5.8rem;
					}
					.remark{
						position: absolute;
						font-size: 0.32rem;
						font-weight: bold;
						color: #4686F2;
						top: 0.9rem;
						left: 0;
						width: 100%;
						&.proposal{
							color: #940C12;
						}
					}
				}
				video{
					width: 5.3rem;
					border-radius: 0.16rem;
				}
			}
		}
		&.client{
    	justify-content: flex-end;
			.item-inner{
				background: #1577FD;
				color: #FFFFFF;
				&::before{
					left: unset;
					right: -0.14rem;
					transform: rotate(180deg);
					border-right-color:#1577FD;
				}
			}
		}
	}
	.iframe-wrapper{
		position: absolute;
		top: 0px;
		left: 0px;
		bottom: 0px;
		width: 100%;
		background: #fff;
		.title{
			line-height: 0.88rem;
			padding-left: 0.3rem;
		}
		iframe{
			width: 100%;
			height: calc(100% - 0.88rem);
		}
	}
}
</style>